package com.ljc.cjgl.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.ljc.cjgl.custom.FileUtil;
import com.ljc.cjgl.entitiy.TbImage;
import com.ljc.cjgl.repository.ImageRepository;

@Service
public class ImageService {
	@Autowired
	private ImageRepository imageDAO;

	public Page<TbImage> findAll(Specification<TbImage> specification, PageRequest pageRequest) {
		return imageDAO.findAll(specification,pageRequest);
	}

	public TbImage findOne(Integer id) {
		return imageDAO.getOne(id);
	}
	
	@Transactional
	public synchronized void save(MultipartFile file, TbImage image) throws IOException {
		TbImage tbImage=new TbImage();
		Integer id=image.getId();
		if(id!=null) {
			tbImage=imageDAO.getOne(id);
		}
		BeanUtils.copyProperties(image, tbImage,"id","filename","uid");
		String fileName = file.getOriginalFilename();
		if(StringUtils.hasText(fileName)) {
			fileName=(new File(fileName)).getName();
	    	tbImage.setFilename(fileName);
	    	String uid=tbImage.getUid();
	    	if(uid==null) {
	    		uid=UUID.randomUUID().toString();
	    		tbImage.setUid(uid);
	    	}
	    	FileUtil.uploadFile(file.getBytes(), uid);
		}
		imageDAO.save(tbImage);
	}

	public TbImage findByUid(String uid) {
		return imageDAO.findByUid(uid);
	}
	
	@Transactional
	public synchronized void delete(List<TbImage> images) {
		for(TbImage image:images) {
			File file=new File(FileUtil.getFilePath(),image.getUid());
			if(file.exists()) {
				file.delete();
			}
			imageDAO.delete(image);
		}
	}
	
	
}
